﻿/*
SharePoint 2010 Search AutoComplete for SharePoint Lists
By: Toni Frankola
http://www.sharepointusecases.com

Version: 1.6.0.0.
*/

ExecuteOrDelayUntilScriptLoaded(Initialize, "SP.js");

var site;
var context;
var list;

String.prototype.format = function () {
    var args = arguments;
    return this.replace(/{(\d+)}/g, function (match, number) {
        return typeof args[number] != 'undefined'
      ? args[number]
      : match
    ;
    });
};

function queryItems(term, response) {
    context = SP.ClientContext.get_current();
    web = context.get_web();
    list = web.get_lists().getByTitle(targetList);

    context.load(web);
    context.load(list);

    var CamlQuery = new SP.CamlQuery();
    CamlQuery.set_viewXml("<View Scope='RecursiveAll'><RowLimit>10</RowLimit><Query><Where>" + camlQuery.format(term) + "</Where></Query></View>");

    items = list.getItems(CamlQuery);

    context.load(items, "Include(" + displayFields + ")");

    context.executeQueryAsync(Function.createDelegate(this, success), Function.createDelegate(this, this.Failed));

    function success(sender, args) {
        var itemEnumerator = items.getEnumerator();
        var listBaseType = list.get_baseType();

        results = new Array();
        var i = 0;

        while (itemEnumerator.moveNext()) {
            var item = itemEnumerator.get_current();

            fieldValues = item.get_fieldValues();
            results[i++] = { label: GetFieldValues(fieldValues), value: GetFieldValues(fieldValues), desc: item.get_id() };
        }

        response(results);
    }
}

function Failed(sender, args) {
    ShowStatusBarMessage('Unexpected Error Occurred with Search AutoComplete for Lists web part:', 'Request failed! ' + args.get_message() + ' ' + args.get_stackTrace());
}

function ShowStatusBarMessage(title, message) {
    var statusId = SP.UI.Status.addStatus(title, message, true);
    SP.UI.Status.setStatusPriColor(statusId, 'red');
}

// Custom String.format for JQuery, source: http://tinyurl.com/ycen4ky
String.format = function () {
    var s = arguments[0];
    for (var i = 0; i < arguments.length - 1; i++) {
        var reg = new RegExp("\\{" + i + "\\}", "gm");
        s = s.replace(reg, arguments[i + 1]);
    }

    return s;
}